package com.link510.aitools.services;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

import androidx.core.app.ActivityCompat;

import com.blankj.utilcode.util.Utils;
import com.orhanobut.logger.Logger;

import java.util.List;


/**
 * wifi模块封装,刘崇科
 */
public class Wifi2Manager {

    private static final int WIFI_CONNECTING = 10;
    private static final int WIFI_CONNECTED = 20;
    private static final int WIFI_CONNECT_FAILED = -100;
    //定义一个WifiLock
    WifiManager.WifiLock mWifiLock;

    private static Wifi2Manager wifi2Manager = null;


    private WifiManager mWifiManager = null;

    private List<ScanResult> mWifiList = null;
    private List<WifiConfiguration> mWifiConfiguration = null;

    public static Wifi2Manager getInstance() {

        if (wifi2Manager == null) {
            synchronized (new Wifi2Manager()) {
                if (wifi2Manager == null) {
                    wifi2Manager = new Wifi2Manager();
                }
            }
        }


        return wifi2Manager;

    }

    /**
     * 构造方法
     */
    private Wifi2Manager() {
        mWifiManager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    }


    /**
     * 关闭WIFI
     */
    public void CloseWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    /**
     * 锁定WifiLock，当下载大文件时需要锁定
     */
    public void AcquireWifiLock() {
        mWifiLock.acquire();
    }

    /**
     * 解锁WifiLock
     */
    public void ReleaseWifiLock() {
        //判断时候锁定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    /**
     * 创建一个WifiLock
     */
    public void CreatWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("Test");
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        mWifiManager.startScan();
        //得到扫描结果
        mWifiList = mWifiManager.getScanResults();
        //得到配置好的网络连接
        if (ActivityCompat.checkSelfPermission(Utils.getApp(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mWifiConfiguration = mWifiManager.getConfiguredNetworks();
    }

    /**
     * 创建wifi
     *
     * @param SSID     ssid
     * @param Password 密码
     * @param Type     类型
     * @return WifiConfiguration
     */
    public WifiConfiguration CreateWifiInfo(String SSID, String Password,
                                            int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";

        WifiConfiguration tempConfig = this.isExsits(SSID);

        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        if (Type == 1) // WIFICIPHER_NOPASS
        {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 2) // WIFICIPHER_WEP
        {
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password + "\"";
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 3) // WIFICIPHER_WPA
        {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }

    /**
     * 判断是否存在ssid
     *
     * @param ssid ssid
     * @return WifiConfiguration 网络配置
     */
    private WifiConfiguration isExsits(String ssid) {

        if (ssid == null) {
            return null;
        }

        if (ActivityCompat.checkSelfPermission(Utils.getApp().getApplicationContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        List<WifiConfiguration> list = mWifiManager.getConfiguredNetworks();

        for (WifiConfiguration result : list) {

            if (result == null) {
                continue;
            }
            if (ssid.equals(result.SSID)) {
                return result;
            }

        }

        return null;
    }


    /**
     * 添加并连接网络
     *
     * @param config 网络配置
     */
    public boolean addNetwork(WifiConfiguration config) {
        int wcgID = mWifiManager.addNetwork(config);
        boolean b = mWifiManager.enableNetwork(wcgID, true);
        System.out.println("a--" + wcgID);
        System.out.println("b--" + b);

        return b;
    }

    /**
     * 判断网络是否连接
     *
     * @return int 网络状态
     */
    public int isWifiContected() {

        ConnectivityManager connectivityManager = (ConnectivityManager) Utils.getApp()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (wifiNetworkInfo == null) {
            return WIFI_CONNECT_FAILED;
        }


        Logger.v("isConnectedOrConnecting = " + wifiNetworkInfo.isConnectedOrConnecting());
        Logger.d("wifiNetworkInfo.getDetailedState() = " + wifiNetworkInfo.getDetailedState());
        if (wifiNetworkInfo.getDetailedState() == NetworkInfo.DetailedState.OBTAINING_IPADDR
                || wifiNetworkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTING) {
            return WIFI_CONNECTING;
        } else if (wifiNetworkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
            return WIFI_CONNECTED;
        } else {
            Logger.d("getDetailedState() == " + wifiNetworkInfo.getDetailedState());
            return WIFI_CONNECT_FAILED;
        }
    }
}
